package cc.cc4414.cc02.system.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cc.cc4414.cc02.core.result.ResultEnum;
import cc.cc4414.cc02.core.result.ResultException;
import cc.cc4414.cc02.system.entity.Authority;
import cc.cc4414.cc02.system.entity.Role;
import cc.cc4414.cc02.system.repository.AuthorityRepository;
import cc.cc4414.cc02.system.repository.RoleRepository;
import cc.cc4414.cc02.system.service.RoleService;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cc 2018年7月15日
 */
@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	private AuthorityRepository authorityRepository;

	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}

	@Override
	public List<Authority> findAuthorityByRoleId(Long roleId) {
		return authorityRepository.findByRoleId(roleId);
	}

	@Override
	public void save(Role role) {
		if (roleRepository.findByName(role.getName()) != null) {
			throw new ResultException(ResultEnum.ROLE_EXISTED);
		}
		// id设置为空save方法才是新增，否则是修改
		role.setId(null);
		try {
			roleRepository.save(role);
		} catch (Exception e) {
			log.warn("新增角色【{}】失败", role.getDescription());
			throw new ResultException(ResultEnum.ROLE_SAVE_ERROR);
		}
	}

	@Override
	public Role findByName(String name) {
		return roleRepository.findByName(name);
	}

	@Override
	public void updateDescription(Long roleId, String description) {
		Optional<Role> optional = roleRepository.findById(roleId);
		if (!optional.isPresent()) {
			log.warn("id为{}的角色不存在", roleId);
			throw new ResultException(ResultEnum.ROLE_NOT_EXIST);
		}
		Role role = optional.get();
		role.setDescription(description);
		roleRepository.save(role);
	}

	@Override
	public void delete(Long roleId) {
		if (!roleRepository.findById(roleId).isPresent()) {
			log.warn("id为{}的角色不存在", roleId);
			throw new ResultException(ResultEnum.ROLE_NOT_EXIST);
		}
		roleRepository.deleteUserRoleByRoleId(roleId);
		roleRepository.deleteRoleAuthorityByRoleId(roleId);
		roleRepository.deleteById(roleId);
	}

	@Override
	public void updateRoleAuthority(Long roleId, Long[] authorityIds) {
		if (!roleRepository.findById(roleId).isPresent()) {
			log.warn("id为{}的角色不存在", roleId);
			throw new ResultException(ResultEnum.ROLE_NOT_EXIST);
		}
		roleRepository.deleteRoleAuthorityByRoleId(roleId);
		if (authorityIds == null) {
			return;
		}
		for (Long authorityId : authorityIds) {
			roleRepository.saveRoleAuthorityByRoleIdAndAuthorityId(roleId, authorityId);
		}
	}

}
